import { HttpException, Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { EntityManager, Repository } from 'typeorm'
import { OrderScoreEntity } from '../entities/order-score.entity'
import { OrderEntity } from '../entities/order.entity'
import { orderScoreDto } from '../dto/order-score.dto'
import { UserEntity } from '@/src/user/entities/user.entity'
import { WalletLogService } from '../../points/points.service'
import { walletType } from '@/mock'
@Injectable()
export class OrderScoreService {
  constructor(
    @InjectRepository(OrderScoreEntity)
    private orderScoreRepo: Repository<OrderScoreEntity>,
    @InjectRepository(OrderEntity)
    private orderRepo: Repository<OrderEntity>,
    private entityManager: EntityManager,
    private walletLogService: WalletLogService,
  ) { }

  // 评价订单
  async createScore(data: orderScoreDto, userId: number) {
    const scoreNum = +data.score
    if (scoreNum < 1 || scoreNum > 5 || !Number.isInteger(scoreNum)) {
      throw new HttpException('评分必须在1-5之间且为整数', 400)
    }

    // 事务处理：评价创建 + 订单状态更新 + 积分发放
    return await this.entityManager.transaction(async (manager) => {
      const order = await manager.findOne(OrderEntity, {
        where: {
          id: data.order_id,
          user_id: userId,
          status: 2
        }
      })
      if (!order) {
        throw new HttpException('订单不存在或未完成，无法评价', 400)
      }

      // 校验是否已评价（避免重复评价）
      const existingScore = await manager.findOne(OrderScoreEntity, {
        where: { order: { id: data.order_id } },
      })
      if (existingScore) {
        throw new HttpException('该订单已评价，无需重复提交', 400)
      }

      // 创建评价记录
      const newScore = manager.create(OrderScoreEntity, {
        ...data,
        order: { id: data.order_id }, // 关联订单
        score: scoreNum
      })
      await manager.save(newScore)

      await manager.update(OrderEntity,
        { id: data.order_id },
        { reviewed: true }
      )

      // 生成5-10随机积分并发放给用户
      const randomReward = Math.floor(Math.random() * (10 - 5 + 1)) + 5

      // 查询用户信息（确保用户存在）
      const user = await manager.findOne(UserEntity, { where: { id: userId } })
      if (!user) {
        throw new HttpException('评价用户不存在，积分发放失败', 500)
      }

      // 累加用户积分
      user.balance += randomReward
      // 记录钱包日志（评价奖励）
      await this.walletLogService.createTransaction(userId, walletType.COMMENT, randomReward)
      await manager.save(user)

      return {
        balance: randomReward
      }
    })
  }

  // 查看评价
  async viewOrderScore(orderId: number, userId: number) {
    // 1. 先校验订单是否属于当前用户
    const order = await this.orderRepo.findOne({
      where: { id: orderId, user_id: userId },
    })
    if (!order) throw new HttpException('订单不存在或无权查看', 404)

    // 2. 查询该订单的评价
    const score = await this.orderScoreRepo.findOne({
      where: { order: { id: orderId } },
    })

    if (!score) throw new HttpException('该订单未评价', 409)
    return {
      // order_id: score.order.id,
      score: score.score,
      comment: score.comment,
      photo_url: score.photo_url,
    }
  }
}